<template>
  <div class="rf-upload-picture">
    <el-upload :action="url" list-type="picture-card" :on-success="handleMoreSuccess" :before-upload="beforeUpload"
      :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :limit="maxLength" :data="params"
      :class="{disabled:uploadDisabled}" :file-list="files" ref="uploadImage">
      <i class="el-icon-plus"></i>
    </el-upload>
    <div class="preview-bg" v-if="previewVisible" @click="previewVisible=false">
      <div class="preview-image">
        <img :src="dialogImageUrl">
      </div>
    </div>
  </div>
</template>
<script>
  import api from '../../../../utils/api'
  export default {
    name: 'RfUploadPict',
    props: {
      maxLength: {
        type: Number,
        default: 1
      },
      imageUrl: {
        type: String
      },
      // 图片上传的宽高限制
      limitOption: {
        type: Object,
        default: () => {
          return {
            width: '',
            height: ''
          }
        }
      },
      // 额外的上传参数
      params: {
        type: Object,
        default: () => {}
      }
    },
    computed: {
      uploadDisabled: function () {
        return this.maxLength < 2 && this.currentPicLegnth > 0
      }
    },
    watch: {
      imageUrl: {
        immediate: true,
        handler (value) {
          if (!!value && value != '') {
            this.files = value.split(',').map(item => {
              return {
                'url': item
              }
            })
          } else {
            this.files = []
          }
          this.currentPicLegnth = this.files.length
        }
      }
    },
    data () {
      return {
        dialogImageUrl: '',
        previewVisible: false,
        url: api.uploadUrl(),
        currentPicLegnth: 0,
        files: [],
        fileData: []
      }
    },
    methods: {
      // 校验图片的尺寸
      beforeUpload (file) {
        if (!this.limitOption.width || !this.limitOption.height) return true
        const isSize = new Promise((resolve, reject) => {
          let width = this.limitOption.width
          let height = this.limitOption.height
          let _URL = window.URL || window.webkitURL
          let img = new Image()
          img.onload = function () {
            let valid = img.width === width && img.height === height
            valid ? resolve() : reject()
          }
          img.src = _URL.createObjectURL(file)
        }).then(() => {
          return file
        }, () => {
          this.$message.error(
            `${this.$t('TIP.PIC_SIZE_LIMIT')}${this.limitOption.width}px x ${this.limitOption.height}px`)
          return Promise.reject()
        })
        return isSize
      },
      // 移除图片操作
      handleRemove (file, fileList) {
        const url = fileList.map(item => {
          if (item.percentage === 100) {
            return item.response.data.data.fileUrl
          } else {
            return item.url
          }
        }).toString()
        this.fileData.forEach((item, index) => {
          if (item.fileUrl === file.url) {
            this.fileData.splice(index, 1)
          }
        })
        this.currentPicLegnth = url.length
        this.getImage(url)
      },
      // 图片预览操作
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.previewVisible = true
      },
      // 图片上传成功操作
      handleMoreSuccess (response, file, fileList) {
        if (response.code === api.SUCCESS) {
          const fileUrl = fileList.map(item => {
            if (item.percentage === 100) {
              return item.response.data.data.file_url
            } else {
              return item.url
            }
          }).toString()
          this.fileData.push(response.data.data)
          this.currentPicLegnth = fileUrl.length
          this.getImage(fileUrl)
        } else {
          this.$message.warning(response.msg)
          this.$refs['uploadImage'].clearFiles()
        }
      },
      // 图片变动传递事件
      getImage (data) {
        const fileIds = this.fileData.map(item => item.file_id).toString()
        this.$emit('getImage', data, fileIds)
      },
      // 清除
      clear () {
        this.$refs['uploadImage'].clearFiles()
        this.files = []
        this.fileData = []
      },
      // 设置fileData
      setFileData (imageUrls, imageIds) {
        if (imageUrls) {
          const idArr = imageIds.split(',')
          this.fileData = imageUrls.split(',').map((item, index) => {
            return {
              fileUrl: item,
              fileId: idArr[index]
            }
          })
        } else {
          this.fileData = []
        }
      }
    },
    mounted () {

    }
  }
</script>
<style lang="scss" scoped>
  .preview-bg {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 9999;

    .preview-image {
      img {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        max-width: 100%;
        max-height: 100%;
      }
    }
  }

  .image-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .image-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
  }

  .image {
    width: 100px;
    height: 100px;
    display: block;
    border-radius: 6px;
  }
</style>
